<template>
    <div>
      <el-card>
        <div class="head">
          <el-button color="#1baeae" style="color: #fff" :icon="Plus" @click="add"
            >添加</el-button
          >
          <el-button
            color="#f56c6c"
            style="color: #fff"
            :icon="Delete"
            @click="dels"
            >批量删除</el-button
          >
        </div>
        <el-table
          @selection-change="changeStatus"
          :data="list"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="categoryName" label="分类名称" />
          <el-table-column prop="categoryRank" label="排序值" />
          <el-table-column prop="createTime" label="添加时间" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button text type="primary" @click="edit(scope.row)"
                >修改</el-button
              >
              <el-button text type="primary" @click="nextCateGory(scope.row)"
                >下级分类</el-button
              >
              <el-popconfirm
                @confirm="del([scope.row.categoryId])"
                title="你确定要删除吗?"
              >
                <template #reference>
                  <el-button text type="primary">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="params.pageNumber"
            v-model:page-size="params.pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :background="background"
            layout=" prev, pager, next"
            :total="total"
            @size-change="getList"
            @current-change="getList"
          />
        </div>
      </el-card>
      <!-- 弹窗 -->
      <el-dialog v-model="dialogFormVisible" :title="title" width="500">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="ruleForm.categoryName" />
          </el-form-item>
          <el-form-item label="排序值" prop="categoryRank">
            <el-input type="number" v-model="ruleForm.categoryRank" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import { api } from "../../../api/api";
  import { Plus, Delete } from "@element-plus/icons-vue";
  import { ElMessage } from "element-plus";
  import "element-plus/es/components/message/style/css";
  
  
  const route = useRoute();
  const router = useRouter();
  const background = ref<boolean>(true);
  const total = ref<number>(0);
  const dialogFormVisible = ref<boolean>(false);
  const title = ref<string>("");
  interface paramsT {
    pageNumber: number;
    pageSize: number;
    categoryLevel: number;
    parentId: number;
  }
  const params = reactive<paramsT>({
    pageNumber: 1,
    pageSize: 10,
    categoryLevel: 3,
    parentId: 0,
  });
  const list = ref<any>([]);
  async function getList() {
    params.parentId = route.query.parent_id ? Number(route.query.parent_id) : 0;
    const res: any = await api.getCategoriesApi(params);
    list.value = res.data.list;
    total.value = res.data.totalCount;
  }
  onMounted(() => {
    getList();
  });
  import type { FormInstance, FormRules } from "element-plus";
  
  interface RuleForm {
    categoryLevel: number;
    categoryName: string;
    categoryRank: string;
    parentId: number;
    categoryId: number;
  }
  
  const formSize = ref("default");
  const ruleFormRef = ref<FormInstance>();
  const ruleForm = reactive<RuleForm>({
    categoryLevel: 3,
    categoryName: "",
    categoryRank: "",
    parentId: 0,
    categoryId: 0,
  });
  
  const rules = reactive<FormRules<RuleForm>>({
    categoryName: [
      { required: true, message: "请输入商品名称", trigger: "blur" },
    ],
    categoryRank: [{ required: true, message: "请输入排序值", trigger: "blur" }],
  });
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        ruleForm.parentId = Number(route.query.parent_id);
        const apiUrl =
          title.value == "添加商品"
            ? api.addCategoriesApi
            : api.editCategoriesApi;
        const info = title.value == "添加商品" ? "添加成功" : "编辑成功";
        apiUrl(ruleForm).then((res: any) => {
          if (res.resultCode == 200) {
            ElMessage.success(info);
            getList();
            dialogFormVisible.value = false;
          } else {
            ElMessage.error(res.message);
          }
        });
      } else {
        console.log("error submit!", fields);
      }
    });
  };
  
  // 删除
  async function del(ids: any[]) {
    const res: any = await api.deleteCategoriesApi({ ids: ids });
    if (res.resultCode == 200) {
      ElMessage.success("删除成功");
      getList();
    } else {
      ElMessage.error(res.message);
    }
  }
  // 批量删除勾选框
  const deleteParams = ref<any[]>([]);
  function changeStatus(e: any) {
    let arr: any[] = [];
    e.forEach((element: any) => {
      arr.push(element.categoryId);
    });
    deleteParams.value = arr;
  }
  // 批量删除
  function dels() {
    del(deleteParams.value);
  }
  
  // 清空表单
  function resetForm() {
    ruleForm.categoryName = "";
    ruleForm.categoryRank = "";
    ruleForm.categoryLevel = 3;
    ruleForm.categoryId = 0;
    ruleForm.parentId = 0;
  }
  // 添加弹窗
  function add() {
    dialogFormVisible.value = true;
    resetForm();
    title.value = "添加商品";
  }
  // 编辑
  function edit(row: any) {
    dialogFormVisible.value = true;
    title.value = "编辑商品";
    ruleForm.categoryName = row.categoryName;
    ruleForm.categoryId = row.categoryId;
    ruleForm.categoryRank = row.categoryRank;
  }
  // 下级分类
  function nextCateGory(row: any) {
    if (row.categoryLevel == 1) {
    router.push({
      path: "/category/level2",
      query: { parent_id: row.categoryId },
    });
  } else if (row.categoryLevel == 2) {
    router.push({
      path: "/category/level3",
      query: { parent_id: row.categoryId },
    });
  }else{
    ElMessage.error("没有下级分类");
  }
  }
  </script>
  
  <style lang="scss">
  .pagination {
    width: 100%;
    display: flex;
    margin: 20px 0;
    justify-content: center;
    align-items: center;
  }
  </style>
  